﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Drawing;

namespace GandA.Web.UI.Controls
{
    [
    AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal),
    ]
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:DatePicker runat=server></{0}:DatePicker>")]
    [ToolboxBitmap(typeof(DatePicker), "DatePicker.png")]
    public class DatePicker : WebControl, IPostBackEventHandler
    {
        private EventHandler _selected_changed;
        private HiddenField _hdn_DatePicker;

        #region Propiedades
        [Bindable(true)]
        [Category("Behavior")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool AutoPostBack
        {
            get
            {
                return ViewState["_AutoPostBack"] == null ? false : (bool)ViewState["_AutoPostBack"];
            }

            set
            {
                ViewState["_AutoPostBack"] = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                return ViewState["_Text"] == null ? string.Empty : ViewState["_Text"].ToString();
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public DateTime? MaxDate
        {
            get
            {
                return ViewState["_MaxDate"] == null ? null : (DateTime?)ViewState["_MaxDate"];
            }

            set
            {
                ViewState["_MaxDate"] = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public DateTime? MinDate
        {
            get
            {
                return ViewState["_MinDate"] == null ? null : (DateTime?)ViewState["_MinDate"];
            }

            set
            {
                ViewState["_MinDate"] = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue(null)]
        [Localizable(true)]
        public DateTime? Value
        {
            get
            {
                DateTime date;
                if (DateTime.TryParse(ViewState["_Text"] == null ? string.Empty : ViewState["_Text"].ToString(), out date))
                {
                    return date;
                }
                return null;
            }

            set
            {
                ViewState["_Text"] = value.HasValue ? value.Value.ToShortDateString() : string.Empty;
            }
        }

        [Bindable(true)]
        [Category("Layout")]
        [DefaultValue("")]
        [Localizable(true)]
        public override Unit Width
        {
            get
            {
                return ViewState["_Width"] == null ? (Unit)50 : (Unit)ViewState["_Width"];
            }

            set
            {
                ViewState["_Width"] = value;
            }
        }

        [Bindable(true)]
        [Category("Layout")]
        [DefaultValue("")]
        [Localizable(true)]
        public override Unit Height
        {
            get
            {
                return ViewState["_Height"] == null ? (Unit)50 : (Unit)ViewState["_Height"];
            }

            set
            {
                ViewState["_Height"] = value;
            }
        }

        [Bindable(true)]
        [Category("Accessibility")]
        [DefaultValue("")]
        [Localizable(true)]
        public override short TabIndex
        {
            get
            {
                return ViewState["_TabIndex"] == null ? (short)50 : (short)ViewState["_TabIndex"];
            }

            set
            {
                ViewState["_TabIndex"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool EnabledValidator
        {
            get
            {
                return ViewState["_EnabledValidator"] == null ? false : (bool)ViewState["_EnabledValidator"];
            }
            set
            {
                ViewState["_EnabledValidator"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool EnabledValidatorExpression
        {
            get
            {
                return ViewState["_EnabledValidatorExpression"] == null ? false : (bool)ViewState["_EnabledValidatorExpression"];
            }
            set
            {
                ViewState["_EnabledValidatorExpression"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue("")]
        [Localizable(true)]
        public string ValidationExpression
        {
            get
            {
                return ViewState["_ValidationExpression"] == null ? string.Empty : ViewState["_ValidationExpression"].ToString();
            }
            set
            {
                ViewState["_ValidationExpression"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue("")]
        [Localizable(true)]
        public string ErrorMessage
        {
            get
            {
                return ViewState["_ErrorMessage"] == null ? string.Empty : ViewState["_ErrorMessage"].ToString();
            }
            set
            {
                ViewState["_ErrorMessage"] = value;
            }
        }
        #endregion

        #region Eventos
        public event EventHandler OnSelectedChanged
        {
            add { _selected_changed += value; }
            remove { _selected_changed -= value; }
        }

        protected virtual void FireSleectedChangedEvent()
        {
            if (_selected_changed != null)
            {
                if (!string.IsNullOrEmpty(_hdn_DatePicker.Value))
                {
                    //int pos = 0;
                    //string[] fechas = _hdn_DatePicker.Value.Split(',');
                    //for (pos = 0; pos < fechas.Length; pos++)
                    //{
                    //    string[] fecha = fechas[pos].Split('/');
                    //    if (fecha.Length == 3)
                    //    {
                    //        this.Value = new DateTime(Convert.ToInt32(fecha[2]), Convert.ToInt32(fecha[1]), Convert.ToInt32(fecha[0]));
                    //        break;
                    //    }
                    //}

                    string[] fecha = _hdn_DatePicker.Value.Split('/');
                    this.Value = new DateTime(Convert.ToInt32(fecha[2]), Convert.ToInt32(fecha[1]), Convert.ToInt32(fecha[0]));
                }
                else
                    this.Value = null;

                _selected_changed(this, new EventArgs());
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            //writer.AddAttribute(HtmlTextWriterAttribute.Onchange, 
            //Page.ClientScript.GetPostBackEventReference(this, String.Empty));
            base.AddAttributesToRender(writer);
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            FireSleectedChangedEvent();
        }
        #endregion

        #region Eventos y Metodos
        
        protected override void OnPreRender(EventArgs e)
        {
            bool linkIncluded = false;
            foreach (Control c in Page.Header.Controls)
            {
                if (c.ID == "StyleControls")
                {
                    linkIncluded = true;
                }
            }
            if (!linkIncluded)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.ID = "StyleControls";
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl(this.GetType(), "GandA.Web.UI.Controls.Controls.css"));
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                Page.Header.Controls.Add(csslink);
            }

            base.OnPreRender(e);

            string resourceName = "GandA.Web.UI.Controls.DatePicker.js";
            ClientScriptManager cs;
            if (this.Page == null)
                cs = this.Parent.Page.ClientScript;
            else
                cs = this.Page.ClientScript;
            cs.RegisterClientScriptResource(typeof(GandA.Web.UI.Controls.DatePicker), resourceName);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(_hdn_DatePicker.Value))
            {
                //int pos = 0;
                //string[] fechas = _hdn_DatePicker.Value.Split(',');
                //for (pos = 0; pos < fechas.Length; pos++)
                //{
                //    string[] fecha = fechas[pos].Split('/');
                //    if (fecha.Length == 3)
                //    {
                //        this.Value = new DateTime(Convert.ToInt32(fecha[2]), Convert.ToInt32(fecha[1]), Convert.ToInt32(fecha[0]));
                //        break;
                //    }
                //}
                string[] fecha = _hdn_DatePicker.Value.Split('/');
                this.Value = new DateTime(Convert.ToInt32(fecha[2]), Convert.ToInt32(fecha[1]), Convert.ToInt32(fecha[0]));
            }
            else
                this.Value = null;

            PostBackOptions p = new PostBackOptions(this);
            if (this.AutoPostBack)
                writer.AddAttribute(HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackEventReference(p));
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID);
            writer.AddAttribute(HtmlTextWriterAttribute.Style, Width.Value <= 0 ? "100px" : "width:" + Width.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.WriteFullBeginTag("input type='text' " + (this.EnabledValidator?"ErrorMessage="+ this.ErrorMessage + ";":"") + " style='width:" + (Width.Value - 30).ToString() + (Width.Type == UnitType.Pixel ? "px" : "%") + "' onchange='esFechaValida(this);setValueHdn(this);" + (this.EnabledValidator ? "ValidObjectDate(this);" : "") + (this.EnabledValidatorExpression ? "ValidExpressionDate(this, '" + this.ValidationExpression + "');" : "") + "' value='" + (this.Value.HasValue ? this.Value.Value.ToString("dd/MM/yyyy") : "") + "' name='" + this.ID + "_txt' id='" + this.ID + "_txt' /");
            //_hdn_DatePicker.RenderControl(writer);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_other");
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID + "_other");
            writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
            base.Render(writer);
            writer.RenderEndTag();
            string _MinDate = string.Empty;
            if (MinDate.HasValue)
            {
                _MinDate = "minDate:\"" + MinDate.Value.ToString("dd/MM/yyyy") + "\"" + (MaxDate.HasValue ? "," : "");
            }
            string _MaxDate = string.Empty;
            if (MaxDate.HasValue)
            {
                _MaxDate = "maxDate:\"" + MaxDate.Value.ToString("dd/MM/yyyy") + "\"";
            }

            writer.Write(@"<script>$('#" + this.ID + "_txt').datepicker({showOn: \"button\", buttonImage: \"images/calendar.gif\", buttonImageOnly: true, dateFormat:\"dd/mm/yy\", " + _MinDate + _MaxDate + "});</script>");
            writer.Write(@"<script> " +
                            "function " + this.ID + "_jsDatePiker() { " +
                                "$('#" + this.ID + "_txt').datepicker({showOn: \"button\", buttonImage: \"images/calendar.gif\", buttonImageOnly: true, dateFormat:\"dd/mm/yy\", " + _MinDate + _MaxDate + "});" +
                            "}" +
                          "</script>");
            writer.Write("<script>Sys.WebForms.PageRequestManager.getInstance().add_endRequest(" + this.ID + "_jsDatePiker)</script>");
        }

        protected override void  OnInit(EventArgs e)
        {
            _hdn_DatePicker = new HiddenField();
            _hdn_DatePicker.ID = this.ID + "_Hidden";
            this.Controls.Add(_hdn_DatePicker);
            base.OnInit(e);
        }

        #endregion
    }
}
